package com.github.yangyishe.p100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Problem49_b {
    public static void main(String[] args) {
        String[] strs=new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = new Problem49_b().groupAnagrams(strs);
        System.out.println("lists = " + lists);
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        // 给每个字符一个hash值，保证其唯一性
        int[] hashs=new int[26];
        for(int i=0;i<26;i++){
            hashs[i]=new Object().hashCode();
        }

        // 如果一个单词中的所有字符代表的hash值均一致，则认为字符串是字母异位词
        Map<Integer,List<String>> hash2WordListMap=new HashMap<>();
        for (String str : strs) {
            int hashVal=0;
            for (char c : str.toCharArray()) {
                hashVal+=hashs[c-'a'];
            }
            hash2WordListMap.putIfAbsent(hashVal,new ArrayList<>());
            hash2WordListMap.get(hashVal).add(str);
        }

        return new ArrayList<>(hash2WordListMap.values());
    }
}
